﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Threading;
using System.Globalization;
using System.Text.RegularExpressions;
using Nivdal.TBP;
using Nivdal.AuxCode;

namespace Nivdal
{
    public partial class Tournament : System.Web.UI.Page
    {
        private string CurrentStageId;
        private int Round;

        protected void Page_Load(object sender, EventArgs e)
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();

            string TournamentId = "";
            if (Request.QueryString["Id"] != null)
                TournamentId = Request.QueryString["Id"];
            else
                Response.Redirect("~/TeamHomePage.aspx");


            if (!IsPostBack)
            {
                TournamentTypeHiddenField.Value = GND.ReadNivdalBoolData("TournamentId", "Nivdal_TournamentIsNT", TournamentId) ? "1" : "0";

                TournamentIdHiddenField.Value = TournamentId;

                TournamentInfoDataSource.SelectParameters.Add("UserId", ou.UserId);
                TournamentInfoDataSource.SelectParameters.Add("TournamentId", TournamentId);
                TournamentInfoDataSource.SelectParameters.Add("Language", ou.Language);

                TournamentDatesDataSource.SelectParameters.Add("UserId", ou.UserId);
                TournamentDatesDataSource.SelectParameters.Add("Language", ou.Language);
                TournamentDatesDataSource.SelectParameters.Add("TournamentId", TournamentId);

                FriendlyWeeksDataSource.SelectParameters.Add("TeamId", ou.TeamId);
                FriendlyWeeksDataSource.SelectParameters.Add("TournamentId", TournamentId);

                TournamentStagesDataSource.SelectParameters.Add("TournamentId", TournamentId);
                TournamentStagesDataSource.SelectParameters.Add("Language", ou.Language);

                CurrentStageId = "0";
                Round = 0;
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    string TournamentName = (TournamentFormView.FindControl("TournamentTitleLabel") as Label).Text;
                    PageNameLabel.Text = TournamentName;
                    Title = Resources.Resource.Default_PageTitle + ", " + TournamentName;
                }
                catch { }
            }
        }

        protected void DatesRowDataBind(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string stageName = (e.Row.FindControl("StageNameHiddenField") as HiddenField).Value;
                string stageId = (e.Row.FindControl("StageIdHiddenfield") as HiddenField).Value;
                string SpecialName = (e.Row.FindControl("SpecialNameHiddenField") as HiddenField).Value;

                if (CurrentStageId != stageId)
                {
                    Round = 1;
                    CurrentStageId = stageId;
                }
                else
                    Round++;

                (e.Row.FindControl("StageRoundLabel") as Label).Text = stageName + " " + RoundLabelText(Round.ToString(), "", SpecialName); 

                if ((e.Row.FindControl("AvailabilityHiddenField") as HiddenField).Value == "0")
                {
                    (e.Row.FindControl("DateLabel") as Label).ForeColor = System.Drawing.Color.Red;
                }
            }
        }

        protected void FriendlyWeeksDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int NumTournamentDates = int.Parse((e.Row.FindControl("NumTournamentGamesHF") as HiddenField).Value);
                int NumBookedDates = int.Parse((e.Row.FindControl("NumBookedDatesHF") as HiddenField).Value);

                if ((NumTournamentDates + NumBookedDates) > 3)
                {
                    Label NumGamesLbl = e.Row.FindControl("NumGamesLabel") as Label;
                    NumGamesLbl.ForeColor = System.Drawing.Color.Red;
                    NumGamesLbl.Text += " *";
                }
            }
        }

        protected void SignupForTournament(object sender, EventArgs e)
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string TournamentId = TournamentIdHiddenField.Value;
            string Password = (TournamentFormView.FindControl("PasswordTextBox") as TextBox).Text.Trim();

            string Answer = GND.ReadNivdalStringData("TournamentId", "UserId", "Password", "Language", "Nivdal_SignupForTournament",
                TournamentId, ou.UserId, Password, ou.Language);
            
            MessageLabel.Text = Answer;
            MessagePanel.Visible = true;

            TournamentFormView.DataBind();
        }


        protected void WithdrawFromTournament(object sender, EventArgs e)
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string TournamentId = TournamentIdHiddenField.Value;

            string Answer = GND.ReadNivdalStringData("TournamentId", "TeamId", "Language", "Nivdal_WithdrawFromTournament", TournamentId, ou.TeamId, ou.Language);
            MessageLabel.Text = Answer;
            MessagePanel.Visible = true;

            TournamentFormView.DataBind();
        }
        protected bool IsNationalTeams()
        {
            return ((TournamentFormView.FindControl("NationalTeamsHiddenField") as HiddenField).Value == "1");
        }

        protected string RoundLabelText(string RoundNumber, string Date, string SpecialName)
        {
            string ReturnValue = Date + " ";
            switch (SpecialName)
            { 
                case "0":
                    ReturnValue += Resources.Resource.Global_Round + " " + RoundNumber;
                    break;
                case "1":
                    ReturnValue += Resources.Resource.Tournament_Final;
                    break;
                case "2":
                    ReturnValue += Resources.Resource.Tournament_Semifinal;
                    break;
                case "3":
                    ReturnValue += Resources.Resource.Tournament_Quaterfinal;
                    break;
            }

            return ReturnValue.Trim();           
            
        }

        protected void NextRoundMatchesCommand(object sender, GridViewCommandEventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            if (e.CommandName == "AddToLive")
            {
                GND.ExecNivdalSQL("MatchId", "UserId", "Nivdal_LiveAddMatchToLive", e.CommandArgument, ou.UserId);
                Response.Redirect("Live.aspx");
            }
            else if (e.CommandName == "Bookmark")
            {
                string Answer = GND.ReadNivdalStringData("BookmarkedMatch", "UserId", "Nivdal_BookmarkMatchSelect", e.CommandArgument, ou.UserId);
                Response.Redirect("Bookmarks.aspx?ConfirmNote=" + Answer);
            }

        }

        protected void StartTournament(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            string Answer = GND.ReadNivdalStringData("TournamentId", "Language", "Nivdal_TournamentStartTournament", TournamentIdHiddenField.Value, ou.Language);

            MessageLabel.Text = Answer;
            MessagePanel.Visible = true;

            TournamentFormView.DataBind();
        }

        protected void SetPrizes(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();

            string PrizesOption = "0";
            try
            {
                Repeater rep = TournamentFormView.FindControl("PrizesSetRepeater") as Repeater;

                foreach (RepeaterItem i in rep.Items)
                {
                    if ((i.FindControl("SelectedRB") as RadioButton).Checked)
                    {
                        PrizesOption = (i.FindControl("OptionIdHF") as HiddenField).Value;
                    }
                }

                GND.ExecNivdalSQL("TournamentId", "PrizesOption", "Nivdal_TournamentSetPrizesOption", TournamentIdHiddenField.Value, PrizesOption);

                TournamentFormView.DataBind();
            }
            catch (Exception ex)
            {
                MessageLabel.Text = ex.Message;
                MessagePanel.Visible = true;
            }
        }

        protected void AddDirector(object sender, EventArgs e)
        {
            TextBox tb = TournamentFormView.FindControl("TournamentDirectorTeamIdTextBox") as TextBox;

            if (tb.Text.Trim().Length >= 5)
            {
                int DirectorTeamId = 0;
                if (int.TryParse(tb.Text.Trim(), out DirectorTeamId))
                {
                    GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                    OnlineUser ou = (OnlineUser)Session["User"];
                    MessageLabel.Text = GND.ReadNivdalStringData("TournamentId", "TeamId", "Language", "Nivdal_AddTournamentDirector", TournamentIdHiddenField.Value, DirectorTeamId, ou.Language);
                    MessagePanel.Visible = true;
                    TournamentFormView.DataBind();
                }
                else
                {
                    MessageLabel.Text = Resources.Resource.Error;
                    MessagePanel.Visible = true;
                }
            }
            else
            {
                MessageLabel.Text = Resources.Resource.Error;
                MessagePanel.Visible = true;
            }
        
        }

        protected void RemoveUser(object sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Remove")
            {
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                OnlineUser ou = (OnlineUser)Session["User"];

                string Answer = GND.ReadNivdalStringData("DirectorId", "ApplicationId", "Language", "Nivdal_TournamentDeclineTeamParticipation", ou.UserId, e.CommandArgument, ou.Language);
                MessageLabel.Text = Answer;
                MessagePanel.Visible = true;

                TournamentFormView.DataBind();
            }
        }

        protected void SetPassword(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();

            if ((TournamentFormView.FindControl("ClearSignupRadioButton") as RadioButton).Checked)
            {
                GND.ReadNivdalStringData("TournamentId", "Password", "Nivdal_TournamentUpdatePassword", TournamentIdHiddenField.Value, "");                
            }
            else if ((TournamentFormView.FindControl("PasswordSignupRadioButton") as RadioButton).Checked)
            {
                GND.ReadNivdalStringData("TournamentId", "Password", "Nivdal_TournamentUpdatePassword", TournamentIdHiddenField.Value, 
                    (TournamentFormView.FindControl("TournamentPasswordTextBox") as TextBox).Text.Trim());
            }

            MessageLabel.Text = Resources.Resource.Tournament_PasswordUpdatedMessage;
            MessagePanel.Visible = true;
            TournamentFormView.DataBind();
        }

        protected void ApproveSelectedTeams(object sender, EventArgs e)
        {
            Repeater wRep = TournamentFormView.FindControl("WaitingDirectorApprovalTeams") as Repeater;
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            foreach (RepeaterItem i in wRep.Items)
            {
                if ((i.FindControl("ApproveCheckBox") as CheckBox).Checked)
                {
                    string AppId = (i.FindControl("ApplicationIdHF") as HiddenField).Value;
                    GND.ReadNivdalStringData("DirectorId", "ApplicationId", "Language", "Nivdal_TournamentApproveTeamParticipation", ou.UserId, AppId, ou.Language);
                }            
            }
            TournamentFormView.DataBind();
        }

        protected void DeclinewSelectedTeams(object sender, EventArgs e)
        {
            Repeater wRep = TournamentFormView.FindControl("WaitingDirectorApprovalTeams") as Repeater;
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            foreach (RepeaterItem i in wRep.Items)
            {
                if ((i.FindControl("ApproveCheckBox") as CheckBox).Checked)
                {
                    string AppId = (i.FindControl("ApplicationIdHF") as HiddenField).Value;
                    GND.ReadNivdalStringData("DirectorId", "ApplicationId", "Language", "Nivdal_TournamentDeclineTeamParticipation", ou.UserId, AppId, ou.Language);
                }
            }
            TournamentFormView.DataBind();
        }
        
        protected void DeleteTournament(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            string Answer = GND.ReadNivdalStringData("TournamentId", "language", "UserId", "Nivdal_DeleteTournament", TournamentIdHiddenField.Value, ou.Language, ou.UserId);

            Response.Redirect("~/AllTournaments.aspx?Message=" + Answer); 
        }

        public bool IsAllowedLive(Object CanAddToLive)
        {
            GlobalFunctions GF = new GlobalFunctions();
            return GF.IsAllowedLive(CanAddToLive);
        }

        protected bool IsPremium()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            return ou.IsPremium;
        }


        protected override void InitializeCulture()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
        }

        protected string TeamHomePageLink()
        {
            return (TournamentTypeHiddenField.Value == "1" ? "~/NationalTeam.aspx?Id=" : "~/TeamHomePage.aspx?TeamId=");

        }
    }
}